<meta charset="UTF-8">

<div id="batchmgr" class="full" style="padding: 10px;">
    <div class="demo-spin-container" v-if="loading">
        <Spin size="large" fix></Spin>
    </div>
    <div class="demo-spin-container" v-if="batchSendCmdLoading">
        <Spin fix>
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>{{$t("bgMgr.sending")}}:{{idx}}/{{tableData.length}}</div>  
        </Spin>
    </div>
    <div class="full">
        <h3 class="h3-title">{{$t("bgMgr.batchMgr")}}</h3>
        <Row>
            <i-col span="6" style="padding: 10px;">
                {{$t("bgMgr.allAevcieList")}} 
            </i-col>
            <i-col span="14" style="padding: 10px;">
                {{$t("bgMgr.selectedDeviceList")}}
            </i-col>
            <i-col span="4" style="padding: 10px;">
                {{$t("bgMgr.transferGroupList")}}
            </i-col>
        </Row>
        <Row>
            <i-col span="6" style="padding: 10px;">
                <div style="line-height: 45px;">
                    <i-input v-model.trim="searchDeviceVal" style="width: 100%;" icon="search"></i-input>
                </div>
                <Tree :data="searchDeviceList" show-checkbox :style="streeStyle" @on-check-change="onCheckChange"></Tree>
            </i-col>
            <i-col span="14" style="padding: 10px;">
                <i-table border ref="table" :columns="columns" :data="tableData" :height="taleHeight"></i-table>
            </i-col>
            <i-col span="4" style="padding: 10px;">
                <Tree :data="treeGroupList" :style="treeStyle"></Tree>
            </i-col>
        </Row>
        <Row>
            <i-col span="24" style="text-align: center;border: 1px solid #DCDEE2;padding: 5px;">
                <i-button @click="handleBatchTransfer" style="margin: 0 10px;">{{$t("bgMgr.batchTransfer")}}</i-button>
                <i-button @click="importModal=true" style="margin: 0 10px;">{{$t("bgMgr.exportDevice")}}</i-button>
                <i-button @click="showBatchModal(1)" style="margin: 0 10px;">{{$t("bgMgr.batchModifyForwardingAddress")}}</i-button>
                <i-button @click="showBatchModal(2)" style="margin: 0 10px;">{{$t("bgMgr.batchEditDueDate")}}</i-button>
                <i-button @click="showBatchModal(3)" style="margin: 0 10px;">{{$t("bgMgr.batchResetPwd")}}</i-button>
                <i-button @click="showBatchModal(4)" style="margin: 0 10px;" v-if="userName == 'admin'">{{$t("bgMgr.batchEditDevType")}}</i-button>
                <i-button @click="showBatchModal(5)" style="margin: 0 10px;">{{$t("bgMgr.batchIssueCmd")}}</i-button>
            </i-col>
        </Row>
        <Modal v-model="importModal" width="700" :title="$t('device.import')">
            <Row>
                <i-col span="12" style="padding: 10px;">
                    <i-input v-model.trim="deviceid" type="textarea" :placeholder="$('device.copyBatchNumber')" :autosize="{minRows: 15,maxRows: 15}"></i-input>
                </i-col>
                <i-col span="12" style="padding: 10px;">
                    <i-input v-model.trim="errorTips" :class="fontColor" type="textarea" disabled :autosize="{minRows: 15,maxRows: 15}"></i-input>
                </i-col>
            </Row>
            <div slot="footer" style="height:40px;">
                <Row>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('device.idLength')}}: &nbsp;</i-col>  
                    <i-col span="5">
                        <input-number v-model.number="idLength" :max="15" :min="8" :editable="false" style="width: 100%;"></input-number>
                    </i-col>
                    <i-col span="8" offset="4">
                        <i-button style="width: 100%" @click="handleBatchImport">{{$t('device.import')}}</i-button>
                    </i-col>
                </Row>
            </div>
        </Modal>
        <Modal v-model="batchModal" width="400" :title="$('bgMgr.batchModification')"> 
            <div v-if="showBatchModalType == 1">
                <Row>
                    <i-col span="4" style="padding-top: 6px;">
                        &nbsp;{{$t('bgMgr.forwardingType')}} : &nbsp;
                    </i-col>
                    <i-col span="20">
                        <i-select v-model="forwardtype">
                            <i-option value="0">{{$t('bgMgr.parseHttp')}}</i-option>  
                            <i-option value="1">{{$t('bgMgr.tcp')}}</i-option>
                        </i-select>
                    </i-col>
                </Row>
                <Row>
                    <i-col span="4" style="padding-top: 6px;">
                        {{$t('device.forwardAddress')}}:
                    </i-col>
                    <i-col span="20">
                        <i-input v-model.trim="forwardurl"></i-input>
                    </i-col>
                </Row>
            </div>
            <Row v-if="showBatchModalType == 2">
                <i-col span="4" offset="4" style="line-height: 32px;">
                    {{$t('monitor.expireTime')}}:
                </i-col>
                <i-col span="12">
                    <date-picker type="date" v-model="expirationDate"></date-picker>
                </i-col>
            </Row>
            <Row v-if="showBatchModalType == 3">
                <i-col span="4" offset="4" style="line-height: 32px;">
                    {{$t('bgMgr.passModel')}}:
                </i-col>
                <i-col span="12">
                    <i-select v-model="resetpasswordtype">
                        <i-option value="1">{{$t('bgMgr.deviceIDlastFour')}}</i-option>
                        <i-option value="2">{{$t('bgMgr.fixedPassword')}}</i-option>  
                    </i-select> 
                </i-col>
            </Row>
            <Row v-if="showBatchModalType == 3 && resetpasswordtype == '2'" style="margin-top: 10px;">
                <i-col span="4" offset="4" style="line-height: 32px;">
                    {{$t('header.newPwd')}}:
                </i-col>
                <i-col span="12">
                    <i-input v-model.trim="newPassword"></i-input>
                </i-col>
            </Row>
            <Row v-if="showBatchModalType == 4">
                <i-col span="4" offset="4" style="line-height: 32px;">
                    {{$t('user.devType')}}: 
                </i-col>
                <i-col span="12">
                    <i-select v-model="deviceType">
                        <i-option v-for="item in deviceTypeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                    </i-select>
                </i-col>
            </Row>
            <div v-if="showBatchModalType == 5">
                <div style="text-align: center;padding:0 0 10px 0;font-weight: 600;font-size: 18px;">{{$t('bgMgr.issueCmd')}}</div> 
                <Row>
                    <i-col span="4" offset="4" style="line-height: 32px;">
                        {{$t('bgMgr.cmdContent')}}:
                    </i-col>
                    <i-col span="12">
                        <i-input v-model.trim="cmdContent"></i-input>
                    </i-col>
                </Row>
                <Row style="margin-top: 10px;">
                    <i-col span="4" offset="4" style="line-height: 32px;">
                        {{$t('bgMgr.pwd')}}:
                    </i-col>
                    <i-col span="12">
                        <i-input v-model.trim="cmdPassword"></i-input>
                    </i-col>
                </Row>
            </div>
            <div slot="footer" style="height:40px;">
                <Row style="margin: 5px 0">
                    <i-col span="24" style="text-align: center;">
                        <i-button @click="handleBatchEdit" style="width:300px;">{{$t("bgMgr.submit")}}</i-button>
                    </i-col>
                </Row>
            </div>
        </Modal>
    </div>
</div>
<script>
    vueInstanse = new Vue({
        el: "#batchmgr",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            batchSendCmdLoading: false,
            idx: 0,
            showBatchModalType: 1, // 1批量地址  2
            importModal: false,
            batchModal: false,
            idLength: 11,
            isOk: false,
            forwardurl: "",
            newPassword: '',
            forwardtype: '0',
            cmdContent: '',
            cmdPassword: '',
            expirationDate: new Date(),
            resetpasswordtype: '1',
            deviceType: '',
            deviceTypeList: [],
            errorTips: '',
            deviceid: '',
            searchDeviceVal: '',
            searchDeviceList: [],
            treeGroupList: [],
            tableData: [],
            columns: [{
                type: 'index',
                width: 60,
            }, {
                title: vRoot.$t('alarm.devName'),  
                key: 'devicename'
            }, {
                title: vRoot.$t('alarm.devNum'),
                key: 'deviceid',
            }, {
                title: vRoot.$t("reportForm.ascriptionUser"),
                key: 'username'
            }, {
                title: vRoot.$t("user.grouping"),
                key: 'groupname'
            }, {
                title: vRoot.$t('alarm.action'),
                width: 85,
                render: function(h, params) {
                    return h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: function() {
                                    vueInstanse.tableData.splice(params.index, 1);
                                }
                            }
                        },vRoot.$t('monitor.delete')) 
                }
            }, {
                title: vRoot.$t('bgMgr.result'), 
                width: 90,
                render: function(h, params) {
                    var result = '',
                        color = '',
                        resultType = params.row.resultType;
                    switch (resultType) {
                        case 0:
                            color = "#2D8CF0"; 
                            result = vRoot.$t('device.actionSucc');  
                            break;
                        case 1:
                            color = "#E4393C";
                            result = vRoot.$t('device.actionFail');
                            break;
                        case 2:
                            color = "#000";
                            result = vRoot.$t('device.notOperated');
                            break;
                        case 3:
                            color = "red";
                            result = vRoot.$t('device.noDevice');
                            break;
                        case 4:
                            color = "red";
                            result = vRoot.$t('device.passwordError');
                            break;
                        case 5:
                            color = "red";
                            result = vRoot.$t('device.abnormalInstructionIssued');
                            break;
                        case 6:
                            color = "red";
                            result = vRoot.$t('monitor.sendCmdNoCache');
                            break;
                        case 7:
                            color = "red";
                            result = vRoot.$t('monitor.sendCmdAlreadyCache');   
                            break;
                        case 8:
                            color = "red";
                            result = vRoot.$t('monitor.changePwdSendCmd');   
                            break;
                    }
                    return h('span', {
                        style: {
                            color: color
                        }
                    }, result);
                }
            }],
            selectedGroupId: null,
            selectedGroupName: null,
            selectedUserName: null,
            taleHeight: 100
        },
        methods: {
            showBatchModal: function(type) {
                this.showBatchModalType = type;
                this.batchModal = true;
                this.forwardurl = '';
                this.newPassword = '';
            },
            handleBatchEdit: function() {
                if (this.tableData.length == 0) {
                    this.$Message.error(vRoot.$t('reportForm.selectDevTip'));  
                    return
                }
                var data = {
                        deviceids: []
                    },
                    me = this;
                if (this.showBatchModalType == 1) {
                    data.action = 'modifyforwardurl';
                    data.forwardtype = Number(this.forwardtype);
                    data.forwardurl = this.forwardurl;
                } else if (this.showBatchModalType == 2) {
                    data.action = 'modifyexpiretime';
                    data.expiretime = new Date(this.expirationDate).getTime();
                } else if (this.showBatchModalType == 3) {
                    data.action = 'resetpassword';
                    if (this.resetpasswordtype == '2') {
                        if (this.newPassword.length >= 4) {
                            data.resetpasswordtype = 2;
                            data.passwordnotmd5 = this.newPassword;
                        } else {
                            this.$Message.error(vRoot.$t('device.pwdLengthTips')); 
                            return;
                        }
                    } else {
                        data.resetpasswordtype = 1;
                    }
                } else if (this.showBatchModalType == 4) {
                    data.action = 'changedevicetype';
                    data.devicetype = this.deviceType;
                } else if (this.showBatchModalType == 5) {
                    this.batchSendCmdLoading = true;
                    var url = myUrls.sendCmd();
                    this.idx = 0;
                    var tableData = deepClone(me.tableData);
                    this.tableData.forEach(function(item) {
                        var deviceid = item.deviceid
                        var data = {
                            "devicetype": vRoot.$children[1].deviceInfos[deviceid].devicetype,
                            "cmdcode": "TYPE_SERVER_TRANS_DATA",
                            "deviceid": item.deviceid,
                            "params": [me.cmdContent],
                            "state": -1,
                            "cmdpwd": me.cmdPassword
                        };
                        utils.sendAjax(url, data, function(resp) {
                            me.idx++;
                            tableData.forEach(function(item) {
                                if (item.deviceid == deviceid) {
                                    if (resp.status === 0) {
                                        item.resultType = 0;
                                    } else if (resp.status === 1) {
                                        item.resultType = 4;
                                    } else if (resp.status === -1) {
                                        item.resultType = 5;
                                    } else if (resp.status === 2) {
                                        item.resultType = 6;
                                    } else if (resp.status === 3) {
                                        item.resultType = 7;
                                    } else if (resp.status === 4) {
                                        item.resultType = 8;
                                    }
                                }
                            });
                            if (me.idx >= tableData.length - 1) {
                                me.tableData = tableData;
                                me.batchSendCmdLoading = false;
                            }
                        }, function() {
                            me.idx++;
                            tableData.forEach(function(item) {
                                if (item.deviceid == deviceid) {
                                    if (resp.status === 0) {
                                        item.resultType = 1;
                                    };
                                }
                            });
                            if (me.idx >= tableData.length - 1) {
                                me.tableData = tableData;
                                me.batchSendCmdLoading = false;
                            }
                        });
                    });
                    me.batchModal = false;
                    return;
                }

                var lock = true;
                this.tableData.forEach(function(item) {
                    if (item.resultType === 3) {
                        lock = false;
                    }
                    data.deviceids.push(item.deviceid);
                });
                if (!lock) {
                    me.$Message.error(vRoot.$t('device.exportErrorTips')); 
                    return;
                }
                var url = myUrls.batchOperate();
                utils.sendAjax(url, data, function(respData) {
                    if (respData.total == respData.success) {
                        me.$Message.success(vRoot.$t('device.actionSucc')); 
                    } else {
                        me.$Message.error(vRoot.$t('message.changeFail') + ' : ' + respData.fail );  
                    }
                    me.updatedActionState(respData.errorrecords);
                    me.batchModal = false;
                });
            },
            handleBatchTransfer: function() {
                if (this.tableData.length == 0) {
                    this.$Message.error(vRoot.$t('reportForm.selectDevTip')); 
                    return;
                }
                if (this.selectedGroupName === null) {
                    this.$Message.error(vRoot.$t('device.selectedTransferGroup'));  
                    return;
                }
                var url = myUrls.batchOperate(),
                    me = this;
                var data = {
                    action: 'move',
                    deviceids: [],
                    targetgroupid: this.selectedGroupId,
                    targetusername: this.selectedUserName,
                }
                var lock = true;
                this.tableData.forEach(function(item) {
                    if (item.resultType === 3) {
                        lock = false;
                    }
                    data.deviceids.push(item.deviceid);
                });
                if (!lock) {
                    me.$Message.error(vRoot.$t('device.exportErrorTips'));
                    return;
                }
                utils.sendAjax(url, data, function(respData) {
                    if (respData.status === 0) {
                        if (respData.total == respData.success) {
                            me.$Message.success(vRoot.$t('device.actionSucc'));
                        } else {
                            var successArr = [];
                            me.$Message.error(vRoot.$t('message.changeFail') + ' : '  + respData.fail);
                        }
                        me.updatedActionState(respData.errorrecords);
                        me.queryDevicesTree();
                    } else {
                        me.$Message.error(respData.cause);
                    }
                });
            },
            updatedActionState: function(errorrecords) {
                this.tableData.forEach(function(item) {
                    if (errorrecords.indexOf(item.deviceid) != -1) {
                        item.resultType = 1;
                    } else {
                        item.resultType = 0;
                    }
                })
            },
            handleBatchImport: function() {
                if (!this.isOk) {
                    this.$Message.error("请添加正确的imeis");
                    return;
                };
                var deviceids = this.deviceid.split('\n').filter(function(item) {
                    if (item) {
                        return item
                    }
                });
                var tableData = [];
                deviceids.forEach(function(deviceid) {
                    var device = utils.deviceInfos[deviceid];
                    if (device) {
                        device.resultType = 2;
                        tableData.push(device)
                    } else {
                        tableData.push({
                            resultType: 3,
                            deviceid: deviceid
                        });
                    }
                });
                this.tableData = this.tableData.concat(tableData);
                this.importModal = false;
            },
            onCheckChange: function(selectArr) {
                var tableData = [];
                selectArr.forEach(function(item) {
                    var deviceid = item.deviceid;
                    if (deviceid) {
                        utils.deviceInfos[deviceid].resultType = 2;
                        tableData.push(utils.deviceInfos[deviceid]);
                    }
                })
                this.tableData = tableData;
            },
            queryDevicesTree: function() {
                this.loading = true;
                var url = myUrls.queryDevicesTree(),
                    me = this;
                var data = {
                    username: userName
                };
                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    if (respData.status === 0) {
                        rootuser = respData.rootuser;
                        me.setTreeDataList(respData.rootuser);
                    }
                });
            },
            setTreeDataList: function(rootuser) {
                this.searchDeviceList = [this.castUsersTreeToDevicesTree(rootuser, true)];
                this.treeDeviceList = deepClone(this.searchDeviceList);
                this.treeGroupList = [this.castUsersTreeToDevicesTree(rootuser, false)];
            },
            filtered: function(textStr) {
                function uniq(array) {
                    var temp = [];
                    for (var i = 0; i < array.length; i++) {
                        if (temp.indexOf(array[i]) == -1) {
                            temp.push(array[i]);
                        }
                    }
                    return temp;
                }
                var newArr = [];
                textStr.split("\n").forEach(function(item) {
                    if (item) {
                        newArr.push(item);
                    }
                })
                return uniq(newArr);
            },
            getDeviceListGroups: function(groups, isNeedDevice, username) {
                var groupsList = [],
                    me = this;
                if (groups != null) {
                    for (var i = 0; i < groups.length; ++i) {
                        var group = groups[i];
                        var groupObj = {
                            title: group.groupname,
                            groupid: group.groupid,

                        }
                        if (isNeedDevice) {
                            groupObj.render = utils.renderGroup;
                        } else {
                            groupObj.render = (function(group, username) {
                                return function(h, params) {
                                    var data = params.data;
                                    return h('span', {
                                        on: {
                                            'click': function() {
                                                me.selectedUserName = username;
                                                me.selectedGroupId = group.groupid;
                                                me.selectedGroupName = group.groupname;
                                            }
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            color: (me.selectedUserName == username && me.selectedGroupId == group.groupid) ? '#2D8CF0' : '#000'
                                        }
                                    }, [

                                        h('span', [
                                            h('Radio', {
                                                props: {
                                                    value: (me.selectedUserName == username && me.selectedGroupId == group.groupid)
                                                },
                                                style: {
                                                    marginRight: '4px'
                                                }
                                            }),
                                            h('Icon', {
                                                props: {
                                                    type: 'ios-folder-open'
                                                },
                                                style: {
                                                    marginRight: '8px'
                                                }
                                            }),
                                            h('span', data.title)
                                        ]),
                                    ])
                                }
                            })(group, username);
                        }
                        if (isNeedDevice && group.devices) {
                            groupObj.children = [];
                            group.devices.forEach(function(device) {
                                groupObj.children.push({
                                    deviceid: device.deviceid,
                                    title: device.devicename,
                                    render: utils.renderDev
                                });
                                utils.deviceInfos[device.deviceid] = {
                                    deviceid: device.deviceid,
                                    devicename: device.devicename,
                                    username: username,
                                    groupid: group.groupid,
                                    groupname: group.groupname,
                                }
                            });
                        }
                        groupsList.push(groupObj);
                    }
                }

                if (groupsList.length == 0) {
                    groupsList.push({
                        title: 'Default',
                        groupid: 0,
                        render: function(h, params) {
                            var data = params.data;
                            return h('span', {
                                on: {
                                    'click': function() {
                                        me.selectedUserName = username;
                                        me.selectedGroupId = 0;
                                        me.selectedGroupName = 'Default';
                                    }
                                },
                                style: {
                                    cursor: 'pointer',
                                    color: (me.selectedUserName == username && me.selectedGroupId == 0) ? '#2D8CF0' : '#000'
                                }
                            }, [
                                h('span', [
                                    h('Radio', {
                                        props: {
                                            value: (me.selectedUserName == username && me.selectedGroupId == 0)
                                        },
                                        style: {
                                            marginRight: '4px'
                                        }
                                    }),
                                    h('Icon', {
                                        props: {
                                            type: 'ios-folder-open'
                                        },
                                        style: {
                                            marginRight: '8px'
                                        }
                                    }),
                                    h('span', data.title)
                                ]),
                            ])
                        }
                    });
                }
                return groupsList;

            },
            doCastUsersTreeToDevicesTree: function(usersTrees, isNeedDevice) {

                var devicesTreeRecord = [];
                if (usersTrees != null && usersTrees.length > 0) {
                    for (var i = 0; i < usersTrees.length; ++i) {
                        var usersTree = usersTrees[i];
                        var username = usersTree.username;
                        var subusers = usersTree.subusers;
                        var currentsubDevicesTreeRecord = {
                            render: utils.renderPerson
                        };
                        currentsubDevicesTreeRecord.title = username;
                        var deviceListGroups = this.getDeviceListGroups(usersTree.groups, isNeedDevice, username);
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers, isNeedDevice);
                            subDevicesTreeRecord = deviceListGroups.concat(subDevicesTreeRecord);
                            currentsubDevicesTreeRecord.children = subDevicesTreeRecord;

                        } else {
                            currentsubDevicesTreeRecord.children = deviceListGroups;

                        }
                        devicesTreeRecord.push(currentsubDevicesTreeRecord);
                    }
                }
                return devicesTreeRecord;
            },
            castUsersTreeToDevicesTree: function(devicesTreeRecord, isNeedDevice) {
                var iViewTree = {
                    render: utils.renderPerson,
                    expand: true,
                };
                if (devicesTreeRecord != null) {
                    var username = devicesTreeRecord.username;
                    var subusers = devicesTreeRecord.subusers;
                    iViewTree.title = username;
                    var deviceListGroups = this.getDeviceListGroups(devicesTreeRecord.groups, isNeedDevice, username);
                    if (username != null && subusers != null && subusers.length > 0) {

                        var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers, isNeedDevice);

                        iViewTree.children = deviceListGroups.concat(subDevicesTreeRecord);

                    } else {
                        iViewTree.children = deviceListGroups;
                    }
                }
                return iViewTree;
            },
            matchingDeviceIds: utils.debounce(function(vm, testIds) {
                var relu = this.getRegularPattern(testIds);
                if (relu.content && relu.errormsg === 'OK') {
                    var guilv = relu.content;
                    var reg = new RegExp("^[a-z0-9a-z]{" + vm.idLength + "}$");
                    if (reg.test(guilv)) {
                        vm.isOk = true;
                        vm.deviceid = guilv + "\n";
                        vm.errorTips = "总数 : 1";
                    } else {
                        var isOk = true; // 数据是否合法！
                        var textStr = "";
                        var array = testIds.split(guilv);
                        var errorStr = "";
                        var idx = null;
                        for (var i = 0; i < array.length; i++) {
                            var line = array[i];
                            if (reg.test(line)) {
                                if (array.length - 1 == i) {
                                    textStr += line;
                                } else {
                                    textStr += line + "\n";
                                }
                            } else {
                                idx = i;
                                if (line.length % vm.idLength === 0) {
                                    var count = line.length / vm.idLength;
                                    var j = 0;
                                    while (count > -1 && j <= count) {
                                        textStr += line.slice(j * vm.idLength, vm.idLength * (j + 1)) + "\n";
                                        j++;
                                        count--;
                                    }
                                } else {
                                    errorStr = array[i - 1] + guilv + array[i];
                                    if (array[i + 1]) {
                                        errorStr += guilv + array[i + 1];
                                    }
                                    isOk = false;
                                }
                            }
                        }
                        vm.isOk = isOk;
                        if (isOk) {
                            var newArr = vm.filtered(textStr)
                            var len = newArr.length;
                            vm.deviceid = newArr.join("\n") + "\n";
                            vm.errorTips = "总数  : " + len;
                        } else {
                            vm.errorTips = ("可能在第" + (idx + 1) + "个ID号不合法或者分隔符不一致; \n" + errorStr);
                        }


                    }

                } else {
                    vm.errorTips = "首个ID号不合法";
                    this.isOk = false;
                }

            }, 500),
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                this.taleHeight = wHeight - 204;
            },
            getDeviceType: function() {
                var me = this;
                var url = myUrls.queryDeviceTypeByUser();
                utils.sendAjax(url, {}, function(resp) {
                    if (resp.status == 0 && resp.devicetypes != null) {
                        resp.devicetypes.forEach(function(item, index) {
                            if (index === 0) {
                                me.deviceType = item.devicetypeid;
                            }
                            me.deviceTypeList.push({
                                value: item.devicetypeid,
                                label: item.typename
                            });
                        })

                    }
                });
            },
            getRegularPattern: function(str) {
                var res = {};
                // var reg = /^[a-z0-9a-z]{15}/;
                var reg = new RegExp("^[A-Z0-9a-z]{" + this.idLength + "}");
                if (reg.test(str)) {
                    if (str.length > this.idLength) {
                        var newStr = str.slice(this.idLength);
                        var i = 0;
                        var charArray = [];
                        while (true) {
                            var char = newStr[i];
                            var isTrue = /[A-Z0-9a-z]/.test(char);
                            if (!isTrue) {
                                charArray.push(char);
                            } else {
                                break;
                            }
                            i++;
                        };
                        if (charArray.length > 0) {
                            res.errormsg = "OK";
                            res.content = charArray.join("");
                        } else {
                            res.errormsg = "start id error!";
                            res.content = null;
                        }
                    } else {
                        if (str.length == this.idLength) {
                            res.errormsg = "OK";
                            res.content = str;
                        } else {
                            res.errormsg = "start id error!";
                            res.content = null;
                        }
                    }
                } else {
                    res.content = null;
                    res.errormsg = "start id error!";
                }
                return res;
            },

            variableDeepSearch: function(treeDataFilter, searchWord, limitcount) {

                var childTemp = [];
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var copyItem = null;
                    var item = treeDataFilter[i];
                    if (item != null) {

                        var isFound = false;

                        if (item.title.indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.indexOf(searchWord) != -1)) {
                            copyItem = item;
                            copyItem.expand = false;
                            isFound = true;
                        }
                        if (isFound == false && item.children && item.children.length > 0) {
                            // item.expand = true;
                            // childTemp.push(item);
                            var rs = that.variableDeepSearch(item.children, searchWord, limitcount);
                            if (rs && rs.length > 0) {
                                copyItem = deepClone(item);
                                copyItem.children = rs;
                                copyItem.expand = true;
                                isFound = true;
                            }
                        }

                        if (isFound == true) {
                            limitcount++;

                            childTemp.push(copyItem);
                            if (limitcount > 10) {
                                break;
                            }
                        }
                    }
                }

                return childTemp;
            }
        },
        computed: {
            fontColor: function() {
                return [this.isOk ? 'succ' : 'error'];
            },
            treeStyle: function() {
                return {
                    'height': this.taleHeight + 'px',
                    'overflow-y': 'auto'
                }
            },
            streeStyle: function() {
                return {
                    'height': (this.taleHeight - 45) + 'px',
                    'overflow-y': 'auto'
                }
            },
            deviceids: function() {
                var deviceids = [];
                this.tableData.forEach(function(item) {
                    deviceids.push(item.deviceid);
                });
                return deviceids;
            }
        },
        watch: {
            deviceid: function(newVal) {
                var exec = /[0-9A-Za-z]/g.exec(newVal);
                if (exec) {
                    var idx = exec.index;
                    var newText = newVal.slice(idx);
                    this.matchingDeviceIds(this, newText);
                } else {
                    this.isOk = false;
                    this.errorTips = vRoot.$t('message.deviceIdTips');
                }
            },
            searchDeviceVal: function(newVal) {

                if (newVal === '') {
                    this.searchDeviceList = this.treeDeviceList;
                } else {
                    var limitcount = 0;
                    this.searchDeviceList = this.variableDeepSearch(this.treeDeviceList, newVal, limitcount);
                }

            }
        },
        mounted: function() {
            var me = this;
            utils.deviceInfos = {};
            this.calcTableHeight();
            this.treeDeviceList = [];
            window.onresize = function() {
                me.calcTableHeight();
            }
            if (rootuser == null) {
                this.queryDevicesTree();
            } else {
                me.setTreeDataList(rootuser);
            }

            this.getDeviceType();
            this.userName = userName;
        },
    })
</script>